import { auth } from 'utils/auth.js';
import { get } from 'utils/request.js';
import { config } from 'config.js';

var mta = require('../../utils/mta_analysis.js');

let configs = config();
// 获取应用实例
const app = getApp(); //  eslint-disable-line no-undef
const delay = (t = 0) => new Promise((resolve) => setTimeout(resolve, t));
var timer = -1;

Page({
    data: {
        isSetGps: false,   //点击看自己位置时的flag
        swiper: {
            list: [],
            indicatorDots: false,
            autoplay: false,
            current: 0,
            dotsClass: [],
            points: []
        },
        map: {
            zoom: 10,
            markers: []
        },
        popup: {
            status: false
        },
        mapHeight: 400,
        currentLatitude: null,
        currentLongitude: null,
        goId: '',
        poi_id: '',
        goLatitude: null,
        goLongitude: null,
        distance: 0,
        distances: 0,
        duration: 0,
        onLine: true,
        noAuth: false,
        province_warn: 0,
        iconPathMap: {
            'green': require('../../images/com/green.png'),
            'greenSelected': require('../../images/com/green-selected.png'),

            'yellow': require('../../images/com/yellow.png'),
            'yellowSelected': require('../../images/com/yellow-selected.png'),

            'red': require('../../images/com/red.png'),
            'redSelected': require('../../images/com/red-selected.png')
        },
        clickMakerStatusId: '',
        tagDisplay: true,
        tagsHeight: 26,
        isOpen: false,
        swiperContainerHeight: 185,
        curTagChange: 0,
        goToiletName: '',
        curIconType: null
    },
    hidePopup(e){
        var that = this;
        that.setData({
            'popup.status': false,
            'province_warn': 0
        })

        that.getData({lat: that.data.currentLatitude, lng: that.data.currentLongitude}, that);


    },
    showPopup(){
        this.setData({
            'popup.status': true
        })
    },
    regionchange(e) {
        console.log(e.type)
    },

    goDetailTap(e) {
        console.log(e)
        //第一期不上了
        var dataset = e.currentTarget.dataset;
        var latitude = dataset.latitude;
        var longitude = dataset.longitude;
        var id = dataset.id
        var nid = dataset.nid
        var iconType =  dataset.icontype
        wx.navigateTo({
            url: `/pages/new-detail/new-detail?latitude=${latitude}&longitude=${longitude}&id=${id}&nid=${nid}&icontype=${iconType}`
        })
    },
    markertap(e) {
        var that = this;
        var id = e.markerId;
        var iconPathMap = that.data.iconPathMap;
        var current;
        that.data.swiper.list.map(function (el, index) {
            var iconType = that.data.map.markers[index].iconType;
            if (id == el.id) {
                current = index;
                that.data.map.markers[index].iconPath = that.getIconPathSelected(iconType, iconPathMap);
            } else {
                that.data.map.markers[index].iconPath = that.getIconPath(iconType, iconPathMap);
            }
        })

        if (that.data.clickMakerStatusId != id) {

            that.setData({
                'swiper.current': current,
                'map.markers': that.data.map.markers
            })
            that.data.clickMakerStatusId = id;
        }

    },
    swiperChangeTap(e){
        var that = this;
        var current = e.detail.current;
        var swiperListItem = that.data.swiper.list[current];
        var dotsClass = [], currentId, goLatitude, goLongitude, distance, distances, duration;
        var iconPathMap = that.data.iconPathMap;
        var swiperListLength = that.data.swiper.list.length;
        for (var i = 0; i < swiperListLength; i++) {
            dotsClass.push('');
        }
        dotsClass[current] = 'on';


        that.data.map.markers.map(function (el, index) {
            var iconType = el.iconType;

            if (swiperListItem.id == el.id) {

                el.width = 48;
                el.height = 58;
                el.iconPath = that.getIconPathSelected(iconType, iconPathMap);
                currentId = el.id;
                goLatitude = swiperListItem.loc.lat;
                goLongitude = swiperListItem.loc.lng;
                distance = swiperListItem.distance;
                distances = swiperListItem.distances;
                duration = swiperListItem.duration;
                that.data.goToiletName = swiperListItem.name;
                that.data.curIconType = iconType
            } else {
                el.width = 27;
                el.height = 33;
                el.iconPath = that.getIconPath(iconType, iconPathMap);
            }
        })

        ////滑动之后还原状态
        this.roateAnimation.rotate(0).step();
        this.downAnimationData.height(30).step();
        this.swiperItemAnimationData.height(232).step();
        var mapHeight = this.data.mapHeight + 40;

        that.setData({
            'map.markers': that.data.map.markers,
            'swiper.dotsClass': dotsClass,
            goId: currentId,
            goLatitude: goLatitude,
            goLongitude: goLongitude,
            currentLatitude: goLatitude,
            currentLongitude: goLongitude,
            distance: distance,
            distances: distances,
            duration: duration,
            roateAnimationData: that.roateAnimation.export(),
            downAnimationData: that.downAnimationData.export(),
            swiperItemAnimationData: that.swiperItemAnimationData.export(),
            tagsHeight: 26,
            swiperItemHeight: 232,
            swiperContainerHeight: 185,
            mapHeight: mapHeight,
            isOpen: false,
            goToiletName: that.data.goToiletName,
            curIconType: that.data.curIconType
        })

    },
    onLoad(options) {

        var q = options.q != 'undefined' && decodeURIComponent(options.q);

        if (q) {
            var qStr = q.split('?')[1];
            if (qStr) {
                var qArr = qStr.split('&');
                if (qArr && qArr.length > 0) {
                    var qFirstArr = qArr[0] && qArr[0].split('=') || [];
                    var qSecondArr = qArr[1] && qArr[1].split('=') || [];

                    if (qFirstArr[1] == 'detail' && qSecondArr[1]) {
                        wx.navigateTo({
                            url: `/pages/toilet-detail/toilet-detail?id=${qSecondArr[1]}`
                        })
                    }
                }

            }
        }

        var that = this;
        var next = function () {
            that.loadToilets();
            var model = app.globalData.systemInfo.model;

            if (model.indexOf('Plus') > -1) {
                that.setData({
                    tagDisplay: false
                })

            } else {
                that.setData({
                    tagDisplay: true
                })
            }
        }
        auth(next, true);

        //统计
        mta.Page.init();
    },
    pickUpTap(e){
        console.log(e.target.dataset.tagcurindex)
        var tagcurindex = e.target.dataset.tagcurindex;

        // this.data.swiper.list.map(function(el,index){
        //   if(index == tagcurindex){
        //     el.tagsChange = true;
        //   }else{
        //     el.tagsChange = false;
        //   }
        // })

        if (!this.data.isOpen) {
            this.roateAnimation.rotate(-180).step();
            this.downAnimationData.height(65).step();
            this.swiperItemAnimationData.height(252).step();

            var mapHeight = this.data.mapHeight - 40;

            this.setData({
                roateAnimationData: this.roateAnimation.export(),
                downAnimationData: this.downAnimationData.export(),
                swiperItemAnimationData: this.swiperItemAnimationData.export(),
                tagsHeight: 68,
                swiperItemHeight: 272,
                currentListIndex: tagcurindex,
                mapHeight: mapHeight,
                swiperContainerHeight: 221,
                isOpen: true
            })

        } else {
            this.roateAnimation.rotate(0).step();
            this.downAnimationData.height(30).step();
            this.swiperItemAnimationData.height(232).step();
            var mapHeight = this.data.mapHeight + 40;

            this.setData({
                roateAnimationData: this.roateAnimation.export(),
                downAnimationData: this.downAnimationData.export(),
                swiperItemAnimationData: this.swiperItemAnimationData.export(),
                tagsHeight: 26,
                swiperItemHeight: 232,
                swiperContainerHeight: 185,
                mapHeight: mapHeight,
                isOpen: false
            })

        }

    },
    onShow(e){
        //确保人员再次移动进行定位，获取经纬度

    },
    onReady(){
        this.mapCtx = wx.createMapContext('Map');
        var roateAnimation = wx.createAnimation({
            transformOrigin: "50% 50%",
            timingFunction: "ease"
        })

        var downAnimationData = wx.createAnimation({
            transformOrigin: "50% 50%",
            timingFunction: "ease"
        })

        var swiperItemAnimationData = wx.createAnimation({
            transformOrigin: "50% 50%",
            timingFunction: "ease"
        })


        this.roateAnimation = roateAnimation;
        this.downAnimationData = downAnimationData;
        this.swiperItemAnimationData = swiperItemAnimationData;


    },
    goPersonalCenter(e){
        wx.navigateTo({
            url: '/pages/complaint-list/complaint-list'
        })
    },
    setGps(e){
        var that = this;
        var lastChanged = wx.getStorageSync('isChanged')
        //  that.loadToilets();
        wx.getLocation({
            type: 'gcj02',
            success: function (res) {
                var latitude = res.latitude;
                var longitude = res.longitude;
                //that.data.currentLatitude =  latitude;
                //that.data.currentLongitude = longitude;
                that.setData({
                    currentLatitude: latitude,
                    currentLongitude: longitude
                })
                that.data.isSetGps = true;
                that.getData({lat: that.data.currentLatitude, lng: that.data.currentLongitude}, that);
            },
            fail: function (res) {

                //关闭loading
                wx.hideLoading();
                //没有权限
                that.setData({
                    noAuth: true
                });
            }
        })

    },
    onRefreshTap(e){
        var that = this;
        that.setData({
            onLine: true
        });
        that.loadToilets();
    },
    getData(obj, context){
        wx.showLoading({
            title: '加载中'
        })
        get({'path': configs.nearBy}, obj).then(function (res) {
            wx.hideLoading();
            console.log(res.data)
            var is_changed = res.data.data.is_changed;
            // // //根据返回的结果marker在地图上面
            var managementData = function (res, context) {
                var outTempData = res.data;

                var nearByData = outTempData.data;
                var province_warn = outTempData.data.province_warn;

                var tempData = context.processData(nearByData, context);

                context.data.mapHeight = app.globalData.systemInfo.screenHeight - 232;

                var dotsClass = [];//swiper大于一个点的时候才会有出现

                if (tempData.swiperList.length > 1) {
                    for (var i = 0; i < tempData.swiperList.length; i++) {
                        if (i == 0) {
                            dotsClass.push('on');
                        } else {
                            dotsClass.push('');
                        }
                    }

                } else {
                    wx.showToast({
                        title: '暂无数据',
                        icon: 'success',
                        duration: 2000
                    })
                    return false;
                }


                var status = province_warn == 1 ? true : false;

                if (!province_warn || wx.getStorageSync('wiiIsTip')) {
                    context.setData({
                        province_warn: 0,
                        'popup.status': false,
                    })
                } else {
                    context.setData({
                        province_warn: province_warn,
                        'popup.status': status,
                    })
                    wx.setStorageSync('wiiIsTip', 1);
                }

                context.setData({
                    'currentLatitude': context.data.currentLatitude,
                    'currentLongitude': context.data.currentLongitude,
                    'map.zoom': tempData.zoom,
                    'map.markers': tempData.markers,
                    'swiper.list': tempData.swiperList,
                    'swiper.dotsClass': dotsClass,
                    'swiper.current': context.data.swiper.current,
                    mapHeight: context.data.mapHeight,
                    swiperItemHeight: 232,
                    distance: tempData.swiperList[0].distance,
                    distances: tempData.swiperList[0].distances,
                    duration: tempData.swiperList[0].duration,
                    goId: tempData.swiperList[0].id,
                    goLatitude: tempData.swiperList[0].loc.lat,
                    goLongitude: tempData.swiperList[0].loc.lng,
                    poi_id: tempData.swiperList[0].poi_id,
                    noAuth: false,
                    onLine: true,
                    goToiletName: tempData.swiperList[0].name,
                    curIconType: tempData.swiperList[0].iconType
                })
                context.mapCtx.moveToLocation();
            }
            wx.setStorageSync('isChanged', is_changed)
            if (context.data.isSetGps) {
                if (lastChanged = is_changed) { //数据不刷新
                    return false;
                } else { //拿到第二次请求的数据来刷新
                    managementData(res, context);
                }
            }
            managementData(res, context); //用第一次请求的数据来刷新

        }, function (res) {
            //关闭loading
            wx.hideLoading();
            //有可能是参数有问题或者是网络
            context.setData({
                onLine: false,
                noAuth: false
            });

        })
    },
    getIconPath(iconType, obj){
        var iconPath,
            iconType = iconType || 1;
        if (iconType == 1) {
            iconPath = obj.green;
        } else if (iconType == 2) {
            iconPath = obj.yellow;
        } else if (iconType == 3) {
            iconPath = obj.red;
        }
        return iconPath;
    },
    getIconPathSelected(iconType, obj){
        var iconPathSelected,
            iconType = iconType || 1;
        if (iconType == 1) {
            iconPathSelected = obj.greenSelected;
        } else if (iconType == 2) {
            iconPathSelected = obj.yellowSelected;
        } else if (iconType == 3) {
            iconPathSelected = obj.redSelected;
        }
        return iconPathSelected;
    },
    processData(obj, context){
        var that = this;
        var markers = [], swiperList = [];
        var points = [];
        var iconPathMap = context.data.iconPathMap;

        for (var i = 0, len = obj.list.length; i < len; i++) {
            var tempListItem = obj.list[i];
            //接口数据变成下划线
            var iconType = tempListItem.icon_type;
            var iconPath = context.getIconPath(iconType, iconPathMap);
            var d = obj.list[i];
            var o = {};
            o.id = i + 1;
            o.latitude = d.loc.lat;
            o.longitude = d.loc.lng;
            o.address = d.addr;
            points.push(o);

            var markersItem = {
                id: tempListItem.id,
                latitude: tempListItem.loc.lat,
                longitude: tempListItem.loc.lng,
                width: 27,
                height: 33,
                iconPath: iconPath,
                iconType: tempListItem.icon_type
            };

            this.setData({
                points: points
            });

            if (i == 0) {
                markersItem.width = 48;
                markersItem.height = 58;
                markersItem.iconPath = context.getIconPathSelected(iconType, iconPathMap);
            }
            console.log(tempListItem.pits);

            var swiperListItem = {
                poi_id: tempListItem.poi_id,
                id: tempListItem.id,
                name: tempListItem.name,
                addr: tempListItem.addr,
                tags: tempListItem.tags,
                busy_status: tempListItem.busy_status,
                loc: tempListItem.loc,
                pits: tempListItem.pits,
                is_ai: tempListItem.is_ai,
                distance: tempListItem.distance,
                distances: tempListItem.distances,
                duration: tempListItem.duration,
                iconType: tempListItem.icon_type
            }

            markers.push(markersItem);
            swiperList.push(swiperListItem)
        }

        var tempData = {
            zoom: obj.zoom,
            markers: markers,
            swiperList: swiperList
        }
        return tempData;
    },
    loadToilets(){
        var that = this;
        console.log('....................................');
        wx.getLocation({
            type: 'gcj02',
            success: function (res) {
                var latitude = res.latitude;
                var longitude = res.longitude;
                that.data.currentLatitude = latitude;
                that.data.currentLongitude = longitude;
                that.getData({lat: that.data.currentLatitude, lng: that.data.currentLongitude}, that);
            },
            fail: function (res) {

                //关闭loading
                wx.hideLoading();
                //没有权限
                that.setData({
                    noAuth: true
                });
            }
        })

    },
    onAbnorTap(e){
        wx.openSetting({
            success: function (res) {
                if (!res.authSetting["scope.userInfo"] || !res.authSetting["scope.userLocation"]) {

                    var that = this;
                    that.loadToilets();
                    var model = app.globalData.systemInfo.model;

                    if (model.indexOf('Plus') > -1) {
                        that.setData({
                            tagDisplay: false
                        })

                    } else {
                        that.setData({
                            tagDisplay: true
                        })
                    }
                }
            }
        })
    },
    quickNavigateTap(e){
        var dataset = e.currentTarget.dataset;
        var latitude = dataset.latitude;
        var longitude = dataset.longitude;
        var currentLatitude = dataset.currentLatitude;
        var currentLongitude = dataset.currentLongitude;
        var iconType = dataset.iconType;
        var name = dataset.name;

        wx.navigateTo({
            url: `/pages/navigate/navigate?latitude=${latitude}&longitude=${longitude}&name=${name}&currentLatitude=${currentLatitude}&currentLongitude=${currentLongitude}&icontype=${iconType}`
        })
    },
    onShareAppMessage (res) {
        return {
            title: '手机帮你找厕所',
            path: '/pages/index/index',
            imageUrl: 'http://app-1254950508.file.myqcloud.com/wx19c89d9b0ffb9a6f.o6zAJs4RQAEb7Ma2GmlJp-oCNfIw.cb375c1d6ef1b125bf8be2b1eebba6c8.png',
            success: function (res) {
                // 转发成功
            },
            fail: function (res) {
                // 转发失败
            }
        }
    }
});
